import { randomBytes } from '../hack'
import { u8ToBase64, u8ToHex } from '../byte'

/**
 * 生成安全的随机字符串
 * @param length 随机字符串长度
 * @param alphanumeric 只包含字幕（去掉base64里面的 '_-=/' 字符
 *
 * 更多功能，参考
 * https://github.com/sindresorhus/crypto-random-string
 */
export function randomString(length: number = 32, alphanumeric: boolean = true) {
  const buf = randomBytes(length)
  let string = u8ToBase64(buf)
  if (alphanumeric === true) {
    string = string.replace(/[\W_]+/g, '')
  } else {
    string = string.replace(/\//g, '_').replace(/\+/g, '-')
  }
  if (string.length < length) {
    // 长度不够，使用16进制填充
    const padLength = length - string.length
    const padString = u8ToHex(randomBytes(padLength))
    return string.padEnd(length, padString)
  }
  return string.substring(0, length)
}
